package com.hsq.ndmall.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.hsq.ndmall.mq.constant.StockRabbitMQ.*;

/**
 * @author 黄四清
 * @version 1.0.0
 * @ClassName StockMqConfig.java
 * @Description TODO
 * @createTime 2021年09月06日 19:40:00
 */
@Configuration
@ConditionalOnProperty(name = "spring.stock.mq.enabled",matchIfMissing = false,havingValue = "true")
public class StockMqConfig {
    /*TODO TTL消息 定时*/
    public static class StockEventConfig {
        /*TODO 1.1个交换机*/
        @Bean
        public TopicExchange stockEventExchange() {
            return new TopicExchange(STOCK_EVENT_EXCHANGE, true, false);
        }

        /*TODO 2.2个队列*/
        /*2.1.普通对队列*/
        @Bean
        public Queue stockReleaseQueue() {
            return new Queue(STOCK_RELEASE_QUEUE, true, false, false);
        }

        /*2.1.TTL队列*/
        @Bean
        public Queue stockLockQueue() {
            return QueueBuilder.durable(STOCK_DELAY_QUEUE).exclusive()
                    .ttl(180000) //1分钟
                    .deadLetterExchange(STOCK_EVENT_EXCHANGE)
                    .deadLetterRoutingKey(STOCK_RELEASE_MSG).build();
        }

        /*TODO 3.2个队列绑定到交换机*/
        @Bean
        public Binding stockLockQueueBinding() {
            return BindingBuilder.bind(stockLockQueue()).to(stockEventExchange()).with(STOCK_LOCK_BINDINGKEY);
        }

        @Bean
        public Binding stockReleaseBinding() {
            return BindingBuilder.bind(stockReleaseQueue()).to(stockEventExchange()).with(STOCK_RELEASE_BINDINGKEY);
        }

        /*TODO 4.库存释放队列绑定到订单交换机*/
        @Bean
        public Binding orderCloseOtherBinding() {
            return BindingBuilder
                    .bind(stockReleaseQueue())
                    .to(new OrderMqConfig.OrderEventConfig().orderEventExchange())
                    .with(ORDER_CLOSE_OTHER_BINDIND_KEY);
        }
    }
}
